//
//  CZRefresh.swift
//  CZRefreshControl
//
//  Created by apple on 16/7/1.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let SCREENW = UIScreen.mainScreen().bounds.width
// 刷新控件的状态枚举
enum CZRefreshType: Int{
    // 正常
    case Normal = 0
    // 下拉中
    case Pulling = 1
    // 刷新中
    case Refreshing = 2
}

let CZRefreshHeight: CGFloat = 50

class CZRefresh: UIControl {
    // 被观察者
    var scrollView: UIScrollView?
    
    var refreshState:CZRefreshType = .Normal{
        didSet{
            switch refreshState{
            case .Normal:
                messageLabel.text = "正常"
                // 如果我们上一个状态为刷新中才开始动画
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= CZRefreshHeight
                    })
                }
                
            case .Pulling:
                messageLabel.text = "下拉中"
            case .Refreshing:
                messageLabel.text = "刷新中"
                // 动画设置contentInset.top
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += CZRefreshHeight
                    }, completion: { (_) -> Void in
                        // 相似发送通知
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -CZRefreshHeight, width: SCREENW, height: CZRefreshHeight))
        setupUI()
    }
    // MARK: - 供外界调用方法
    func endRefreshing(){
        refreshState = .Normal
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.orangeColor()
        addSubview(messageLabel)
        //tableView.contentOffset.y
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        messageLabel.frame = CGRect(x: 0, y: 0, width: SCREENW, height: CZRefreshHeight)
    }
    /*
    // 其控制器可能会使用tableView 的代理方法 由于代理是一对一 考虑到封装性 我们不能占用其代理

    KVO的使用比较简单，基本上都是三步：
     
    1.注册观察者
    addObserver:forKeyPath:options:context:
    2.
    观察者中实现
    observeValueForKeyPath:ofObject:change:context:
    3.
    移除观察者
    removeObserver:forKeyPath:
    */
    // 监听该类将要添加在在哪个View上
    override func willMoveToSuperview(newSuperview: UIView?) {
//        print(newSuperview)
        // 判断是否有值 而且是否可以滚动
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        
        self.scrollView = scrollView
        // 注册观察者
        /*
            - 被观察者
                - 观察着
                - 属性
                - 观察属性变化（old new）
        */
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    //观察者中实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // contentOffset.y
        let contentOffSetY = self.scrollView!.contentOffset.y
        // 判断scrollView 是否在拖动
        let contentInsetTop = self.scrollView!.contentInset.top
//        print(contentInsetTop)
        // 代表拖动中
        if scrollView!.dragging{
            if contentOffSetY > -contentInsetTop - CZRefreshHeight  && refreshState == .Pulling{
//                print("正常")
                refreshState = .Normal
            }else if contentOffSetY <=  -contentInsetTop - CZRefreshHeight && refreshState == .Normal {
//                print("下拉中")
                refreshState = .Pulling
            }
            
        }else {
            // 用户松手
            //如果用户停止拖动 而且松手 而且控件的状态为下拉中
            if refreshState == .Pulling{
                refreshState = .Refreshing
            }
        }
    }
    
    // MARK: -  懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFontOfSize(15)
        lab.textColor = UIColor.whiteColor()
        lab.textAlignment = .Center
        lab.text = "正常"
        return lab
    }()
    
    deinit{
       self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
